﻿using System;
using System.Collections;
using UnityEngine;
using UniRx;
public class ControllerSwordUniRX : MonoBehaviour
{
    public Material mat;
    public float disolveTime = 3.0f;
    void Start()
    {
        Observable.EveryUpdate()
        .Where(_ => Input.GetMouseButtonDown(0))
        .Subscribe(_ =>
        {
            Observable.FromCoroutine<float>((observer) => StartDisolveForFromCoroutine(observer, 6.75f)).Subscribe(x =>
            {
                mat.SetFloat("_Disolve", x);
            }, onCompleted: () =>
            {
                Debug.Log("剑已出鞘");
            });
        });
        
        
        Observable.EveryUpdate()
        .Where(_ => Input.GetMouseButtonDown(1))
        .Subscribe(_ =>
        {
            Observable.FromCoroutine<float>((observer) => StartDisolveForFromCoroutine(observer, -0.2f)).Subscribe(x =>
            {
                mat.SetFloat("_Disolve", x);
            }, onCompleted: () =>
            {
                Debug.Log("剑已入鞘");
            });
        });
    }
    IEnumerator StartDisolveForFromCoroutine(IObserver<float> observer, float target)
    {
        float temp = 0;
        float disolve = mat.GetFloat("_Disolve");
        float tempDisolveValue = 0;
        while (temp < disolveTime)
        {
            yield return null;
            tempDisolveValue = Mathf.Lerp(disolve, target, temp / disolveTime);
            observer.OnNext(tempDisolveValue);
            temp += Time.deltaTime;
        }
        observer.OnCompleted();
    }
}
